package vip.xiaozhao.paotui.controller.process;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import vip.xiaozhao.paotui.controller.BaseController;
import vip.xiaozhao.paotui.intf.dto.ResponseDO;
import vip.xiaozhao.paotui.intf.entity.PaotuiDetail;
import vip.xiaozhao.paotui.intf.entity.PaotuiDetailAudit;
import vip.xiaozhao.paotui.intf.enums.*;
import vip.xiaozhao.paotui.intf.service.PaotuiAuditService;
import vip.xiaozhao.paotui.intf.service.PaotuiDetailService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/process/")
@Slf4j
public class PaotuiProcessController extends BaseController {

    @Resource
    private PaotuiAuditService paotuiAuditService;
    @Resource
    private PaotuiDetailService paotuiDetailService;

    //跑腿过程
    @RequestMapping("/addAudit")
    public ResponseDO loadById(int paotuiStatus, int paotuiId , String pics,  HttpServletRequest request, HttpServletResponse response) {
        log.info("load paotui  , id =: "  + paotuiId + " paotuiSatus=:" + paotuiStatus);

        if(paotuiId <= 0){
            ResponseDO.fail("请求参数不正确");
        }

        //2 用户需要登录
        int currentUserId = getCurrentUserId(request);
        if (currentUserId == 0) {
            log.info("user does not login in");
            return ResponseDO.fail(NOT_LOGIN);
        }

        PaotuiDetail detail = paotuiDetailService.loadById(paotuiId);
        if(detail == null || PaotuiGoingStatusEnum.isEndedStatus(PaotuiGoingStatusEnum.getById(paotuiStatus))){
            return ResponseDO.fail("跑腿任务不正常");
        }
        //3.1 当前用户状态判断
        PaotuiGoingStatusEnum statusEnum = PaotuiGoingStatusEnum.getById(paotuiStatus);
        if(statusEnum == null){
            return ResponseDO.fail("订单状态不正确");
        }

        //3.2 当前状态是否正常，状态间具有连续性
        //暂时不处理
        //PaotuiDetailAudit latestStatus = paotuiAuditService.loadLatestByUserIdAndPaotuiId(currentUserId, paotuiId );


        //4 insert 入库，返回前台true
        PaotuiDetailAudit audit = new PaotuiDetailAudit();
        audit.setPaoUserId(statusEnum.getRoleId() ==1 ? currentUserId:0);
        audit.setFaBuUserId(statusEnum.getRoleId() ==2 ? currentUserId:0);
        audit.setPaotuiId(paotuiId);
        audit.setStatus(statusEnum.getId());
        audit.setDesc(statusEnum.getName());
        if(!StringUtils.isEmpty(pics)){
            audit.setImgs(pics);
        }

        paotuiAuditService.insert(audit);
        //5 更新detail表的最新状态
        detail.setStatus(statusEnum.getId());
        paotuiDetailService.update(detail);

        return ResponseDO.success("");
    }



}
